using System;
using System.Collections.Generic;
using OFX.Aggregator.WebScraping.Infrastructure;

namespace OFX.Aggregator.WebScraping.Implementation.BESnet.CreditCard.HtmlPageProcessing
{
	public class BESnetCreditCardStatementPageProcessor : IHtmlPageProcessor
	{
		#region Implementation of IHtmlPageProcessor

		private const string exitSiteAddress = "tpl.asp?SRV=00801";

		public void TestAssumptions(IHtmlDocument document)
		{
			try
			{
				if (document.Frames.Count != 3)
				{
					throw new AssumptionFailedException(this,
					                                    string.Format("Expected 3 IFRAMEs in page, found {0}.",
					                                                  document.Frames.Count));
				}

				IHtmlFrameWindow frame = document.Frames[1];
				IList<IHtmlFrameWindow> iframeCollection = frame.Document.Frames;

				if (iframeCollection.Count != 1)
				{
					throw new AssumptionFailedException(this,
					                                    string.Format("Expected 1 IFRAME in page, found {0}.", iframeCollection.Count));
				}

				IHtmlFrameWindow innerFrame = iframeCollection[0];
				IHtmlDocument innerDocument = innerFrame.Document;
				IHtmlElement pagina = innerDocument.GetElementById("PAGINA");
				if (pagina == null)
				{
					throw new AssumptionFailedException(this, "Expected 'PAGINA' element not found in page!");
				}

				// Find the Exit button
				bool foundExitButton = false;
				IHtmlElementCollection anchorTags = frame.Document.All.Tags("a");
				foreach (IHtmlElement anchor in anchorTags)
				{
					string href = anchor.GetAttribute("href");

					if (!string.IsNullOrEmpty(href) && href.Contains(exitSiteAddress))
					{
						foundExitButton = true;
						break;
					}
				}

				if (!foundExitButton)
				{
					throw new AssumptionFailedException(this, "Expected exit button 'A' element not found in page!");
				}
			}
			catch (InvalidCastException e)
			{
				throw new AssumptionFailedException(this, "Element found was of different type than expected!", e);
			}
		}

		public void ProcessPage(IHtmlDocument document, IHtmlPageProcessorFinished finished)
		{
			IHtmlFrameWindow frame = document.Frames[1];

			IList<IHtmlFrameWindow> iframeCollection = frame.Document.Frames;

			IHtmlFrameWindow innerFrame = iframeCollection[0];
			IHtmlDocument innerDocument = innerFrame.Document;
			IHtmlElement pagina = innerDocument.GetElementById("PAGINA");
			string html = pagina.OuterHtml;

			// Find the Exit button
			IHtmlElementCollection anchorTags = frame.Document.All.Tags("a");
			foreach (IHtmlElement anchor in anchorTags)
			{
				string href = anchor.GetAttribute("href");

				if (!string.IsNullOrEmpty(href) && href.Contains(exitSiteAddress))
				{
					anchor.Click();
					break;
				}
			}

			finished.Finish(html);
		}

		#endregion
	}
}